<template>
    <div class="dashboard-wrap">

        <div class="grid-2x2">
            <div class="card">
                <div ref="genderChartRef" class="chart" />
            </div>

            <div class="card">
                <div ref="ageChartRef" class="chart" />
            </div>

            <div class="card">
                <div class="table-wrap">
                    <el-table
                        :data="treatmentTable"
                        stripe
                        size="small"
                        style="width: 100%"
                    >
                        <el-table-column
                            prop="treatment"
                            label="Treatment"
                            width="220"
                        >
                            <template #default="{ row }">
                                <span
                                    class="color-dot"
                                    :style="{
                                        background: colorOf(row.treatment),
                                    }"
                                ></span>
                                <span>{{ row.treatment }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="count"
                            label="Count"
                            width="100"
                        />
                        <el-table-column
                            prop="proportion"
                            label="Proportion"
                            width="120"
                        >
                            <template #default="{ row }">{{
                                toPercent(row.proportion)
                            }}</template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <div class="card">
                <div class="table-wrap">
                    <el-table
                        :data="subtypeTable"
                        stripe
                        size="small"
                        style="width: 100%"
                    >
                        <el-table-column
                            prop="subtype"
                            label="Subtype"
                            width="220"
                        >
                            <template #default="{ row }">
                                <span
                                    class="color-dot"
                                    :style="{
                                        background: colorOf(row.subtype),
                                    }"
                                ></span>
                                <span>{{ row.subtype }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="count"
                            label="Count"
                            width="100"
                        />
                        <el-table-column
                            prop="proportion"
                            label="Proportion"
                            width="120"
                        >
                            <template #default="{ row }">{{
                                toPercent(row.proportion)
                            }}</template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <div v-if="loading" class="loading">loading...</div>
        <div v-if="error" class="error">{{ error }}</div>
    </div>
</template>

<script setup lang="ts" name="Home">
    import { ref, onMounted, onBeforeUnmount } from "vue";
    import * as echarts from "echarts";
    import "element-plus/dist/index.css";
    import { get, post } from '@/axios/api';

    // 状态
    const genderChartRef = ref(null);
    const ageChartRef = ref(null);
    let genderChart:any = null;
    let ageChart:any = null;

    const loading = ref(false);
    const error = ref(null);
    const treatmentTable = ref([]);
    const subtypeTable = ref([]);

    // API 地址
    const API_URL = "/api/clinical_stats";

    // 配色调色板（可扩展）
    const palette = [
        "#4caf50",
        "#2196f3",
        "#ff9800",
        "#9c27b0",
        "#f44336",
        "#00bcd4",
        "#8bc34a",
        "#ff5722",
    ];

    function toPercent(x:any) {
        if (x === null || x === undefined) return "-";
        return (Number(x) * 100).toFixed(1) + "%";
    }

    function colorOf(name:any) {
        if (!name) return "#999";
        // 简单哈希把同一 name 映射到固定颜色
        let hash = 0;
        for (let i = 0; i < name.length; i++)
            hash = (hash << 5) - hash + name.charCodeAt(i);
        hash = Math.abs(hash);
        return palette[hash % palette.length];
    }

    async function fetchStats() {
        loading.value = true;
        error.value = null;
        try {
            const res:any = await get('/chart/clinical_stats/')
            if (!res || !res.success) throw new Error(`Failed to fetch: ${res.status}`);

            // 渲染图表
            renderGenderChart(res.gender || []);
            renderAgeChart(res.age || []);

            // 表格数据：后端需返回 count 与 proportion（fraction 0-1）
            treatmentTable.value = (res.treatment_table || []).map((r:any) => ({
                ...r,
            }));
            subtypeTable.value = (res.subtype_table || []).map((r:any) => ({ ...r }));
        } catch (err:any) {
            error.value = err.message || String(err);
        } finally {
            loading.value = false;
        }
    }

    function renderGenderChart(genderData:any) {
        if (!genderChartRef.value) return;
        if (!genderChart) genderChart = echarts.init(genderChartRef.value);
        const option = {
            title: {
                text: "Sex Distribution",
                left: "center",
                top: 12,
                textStyle: { fontSize: 16 },
            },
            tooltip: { trigger: "item", formatter: "{b}: {c} ({d}%)" },
            legend: { orient: "horizontal", bottom: 8 },
            series: [
                {
                    name: "Sex",
                    type: "pie",
                    radius: ["36%", "58%"],
                    center: ["50%", "48%"],
                    data: genderData,
                },
            ],
        };
        genderChart.setOption(option);
    }

    function renderAgeChart(ageData:any) {
        if (!ageChartRef.value) return;
        if (!ageChart) ageChart = echarts.init(ageChartRef.value);
        const categories = ageData.map((x:any) => x.name);
        const values = ageData.map((x:any) => x.value);
        const option = {
            title: {
                text: "Age Distribution",
                left: "center",
                top: 12,
                textStyle: { fontSize: 16 },
            },
            tooltip: {
                trigger: "axis",
                formatter: (params:any) =>
                    `${params[0].axisValue}<br/>total: ${params[0].value}`,
            },
            xAxis: {
                type: "category",
                data: categories,
                axisTick: { alignWithLabel: true },
            },
            yAxis: { type: "value", minInterval: 1 },
            grid: { left: 40, right: 20, bottom: 40, top: 60 },
            series: [
                {
                    name: "total",
                    type: "bar",
                    data: values,
                    label: { show: true, position: "top" },
                    barMaxWidth: 24,
                    barMinWidth: 24
                },
            ],
        };
        ageChart.setOption(option);
    }

    function resizeAll() {
        try {
            genderChart && genderChart.resize();
            ageChart && ageChart.resize();
        } catch (e) {}
    }

    onMounted(() => {
        fetchStats();
        window.addEventListener("resize", resizeAll);
    });
    onBeforeUnmount(() => {
        window.removeEventListener("resize", resizeAll);
        genderChart && genderChart.dispose();
        ageChart && ageChart.dispose();
    });
</script>

<style scoped >
    .dashboard-wrap {
        padding: 18px;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
            "Helvetica Neue", Arial;
        color: #222;
    }
    .page-title {
        font-size: 20px;
        margin-bottom: 12px;
    }

    /* 2x2 网格 */
    .grid-2x2 {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
    }

    .card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 6px 18px rgba(35, 45, 65, 0.06);
        padding: 12px;
        display: flex;
        flex-direction: column;
    }
    .card-header h3 {
        margin: 0 0 8px 0;
        font-size: 14px;
        color: #333;
    }
    .chart {
        height: 300px;
        width: 100%;
    }
    .table-wrap {
        padding: 6px 0;
    }
    .color-dot {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        margin-right: 8px;
        vertical-align: middle;
    }
    .loading,
    .error {
        margin-top: 12px;
        color: #666;
    }
    .error {
        color: #c00;
    }

    /* 响应式：小屏时 1 列 */
    @media (max-width: 900px) {
        .grid-2x2 {
            grid-template-columns: 1fr;
        }
    }
</style>
